// pages/departAdd/departAdd.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {    
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //省市区相关
    showProvince:false,
    provinceId:null,
    provinceName:'',
    provinceObj:null,
    showCity:false,
    cityId:null,
    cityName:'',
    cityObj:null,
    showDistrict:false,
    districtId:null,
    districtName:'',
    districtObj:null,
    valueSearchProvince:'',
    valueSearchCity:'',
    valueSearchDistrict:'',
    //父级选择框
    showFather:false,
    //父级选择数据
    fatherList:[],
    //搜索父级
    valueSearchFather:'',
    //大区选择框
    showRegion:false,
    //大区选择数据
    regionList:[],
    //搜索大区
    valueSearchRegion:'',
    //保洁供应方选择框
    showClean:false,
    //保洁供应方选择数据
    cleanList:[],
    //搜索保洁供应方
    valueSearchClean:'',
    //当前用户
    user:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    
    this.setData({
      user: user,
      code: Base64.encode(new Date() + user.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('项目传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取修改的数据
        this.getInfo();
      }else{
        this.setData({
          editInfo: paramObj
        })
      }
    }
    
    //默认勾选物业项目
    let isProject='editInfo.isProject';
    this.setData({
      [isProject]: true
    })
  },

  //提交表单###
  onConfirmAdd(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
    
    let user=app.globalData.userInfo;
    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let flag=true;

    //项目名称必填
    let name=obj.name.trim();
    if(!this.formNotEmpty(name,'nameMessage','请输入项目名称')){
      return;
    }

    if(td.isEdit && editInfo.name==name){
    }else{
      //项目名是否重复
      flag=this.isExist(name).then(value => {
        if(value){
          this.setData({
            nameMessage: '此项目已存在',
            disabled: true
          })
        }
        return !value;
      });
    } 
    
    //上级部门必填
    if(!editInfo.fid){
      Toast.fail('请选择上级部门');
      return;
    }

    //省市区必填
    if(td.provinceObj && JSON.stringify(td.provinceObj)!='{}' && td.cityObj && JSON.stringify(td.cityObj)!='{}' && td.districtObj && JSON.stringify(td.districtObj)!='{}'){
    }else{
      Toast.fail('省市区未填写完整');
      return;
    }

    //权限
    let authArrs=[user.depart, user.departObj[0].companyId, td.id, editInfo.companyId, editInfo.fid, editInfo.regionId];
    let authArr=[];
    authArrs.forEach(item => {
      if(item){
        authArr.push(item);
      }
    });
    let authSet=new Set(authArr);
    authArr=Array.from(authSet);

    //大区未选，加个默认值-上级部门
    if(!editInfo.regionId){
        editInfo.regionId=editInfo.fid;
        editInfo.rid=editInfo.fid;
    }

    //字段
    let param={
      className:'depart',
      data:{
        requestToken: td.code,
        id: td.id,
        //项目名称
        name: name,
        //简称
        nickName: obj.nickName.trim(),
        //地区
        area:{
          province: td.provinceObj,
          city: td.cityObj,
          district: td.districtObj,
        },
        //地址
        addressDetail: obj.addressDetail.trim(),
        //顶级部门
        companyId: editInfo.companyId,
        //合伙人
        partnerId: editInfo.partnerId,
        //上级部门
        fid: editInfo.fid,
        //后台结构树级别
        level: editInfo.level,
        //数据权限
        dataAuthority: {
          depart: authArr
        },
        //大区id
        rid: editInfo.rid,
        //大区id
        regionId: editInfo.regionId,
        //是否物业项目
        isProject: editInfo.isProject,
        //是否大区
        isRegion: editInfo.isRegion,
        //是否是保洁供应方
        isCleaningSupplier: editInfo.isCleaningSupplier,
        //保洁供应方        
        cleaningSupplier: editInfo.cleaningSupplier  
      }
    }
    
    //只限添加时
    if(!td.isEdit){
      //创建人
      param.data.createUser=app.globalData.userInfo;
      //类型，只能客户
      param.data.type=4;
      //后台树用到的
      param.data.hasChildren=false;
      //后台树用到的？
      param.data.count=0;
    }

    Promise.all([flag]).then(value => {
      let passed=value.every(val=>{
        return val;
      });
      if(passed){
        // console.log('~添加项目~');
        // console.log(param.data);
        // return;

        //避免表单重复提交
        Toast.loading({
            duration: 0,
            forbidClick: true,
            message: '数据提交中...'
          }); 

        CommonService.goSave(param).then(res=>{
          if (res.statusCode == 200 && res.data.success == true){
            Toast.success('成功');
            this.setData({
              disabled:false
            })

            //更新上级部门
            this.updateFather(editInfo.fid);

            //关联查询字段更新到设备表
            this.updateEquipment(res.data.data);

            //同步pcsql数据库
            this.syncPcsql(res.data.data.id);

            setTimeout(() => {
              //返回操作
              this.backAndRefresh();
            }, 1000);
            
          }else if(res.statusCode==202){
            Toast.fail('您操作太快了,请勿重复提交');
          }
        }).catch((error) => {
          Toast.clear();
        })
      }
    });  
  },

  //获取项目信息
  getInfo(){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        id:this.data.id,
        selectFields: ['id','name','nickName','addressDetail','area','companyId','partnerId','fid','level','rid','regionId','isProject','isRegion','isCleaningSupplier','cleaningSupplier']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];

        //查询父级名称
        if(result.fid){
          this.getDepartName(result.fid).then(value => {
            if(value){
              let fatherName='editInfo.fatherName';
              this.setData({
                [fatherName]:value 
              })
            }
          });
        }

        //查询大区名称
        if(result.rid){
          this.getDepartName(result.rid).then(value => {
            if(value){
              let regionName='editInfo.regionName';
              this.setData({
                [regionName]:value 
              })
            }
          });
        }  

        //查询保洁供应方名称
        if(!result.isCleaningSupplier && result.cleaningSupplier && result.cleaningSupplier.length){
          this.getDepartName(result.cleaningSupplier[0]).then(value => {
            if(value){
              let cleanName='editInfo.cleanName';
              this.setData({
                [cleanName]:value 
              })
            }
          });
        }

        console.log('修改项目信息回显');
        console.log(result);

        this.setData({
          editInfo: result
        })

        //编辑设备时获取各个字段的值
        this.getInputValue();
      }
    }).catch((error) => {
    })
  },

  //编辑设备时获取各个字段的值
  getInputValue(){
    let info=this.data.editInfo;  

    this.setData({
      provinceName:info.area.province.name,
      cityName:info.area.city.name,
      districtName:info.area.district.name,
      provinceObj:info.area.province,
      provinceId:info.area.province.id,
      cityObj:info.area.city,
      cityId:info.area.city.id,
      districtObj:info.area.district,
      districtId:info.area.district.id
    })
  },

  //返回操作
  backAndRefresh(){
    //获取列表页对象
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    if(prevPage.route=='pages/equipmentAdd/equipmentAdd'){
      //添加设备-查询项目
      prevPage.getProjectData();
    }

    if(prevPage.route=='pages/departList/departList'){
      //刷新列表页数据
      prevPage.refreshListAndPage();
    }

    //返回上一页
    wx.navigateBack();
  },

  //判断表单非空（涉及到数据提交，field可以在调用前去空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //显示省
  onShowProvince(){
    this.setData({
			showProvince: true
    })
    //查询省
    this.findProvince();
  },

  //查询省
  findProvince(){
    let param = {
      isAuth: false,
      className: 'city',
      data: {
        searchAll: true,
        level:'1',		
        selectFields: ['id','name']
      }
    }

    //名称模糊查询
    if(this.data.valueSearchProvince){
      param.data.name='%'+this.data.valueSearchProvince+'%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          provinceList: arr
        })
      }  
    }).catch((error) => {                
    })
  },

  //隐藏省
  onCloseProvince(){
    this.setData({
			showProvince: false
    })
  },

  //确认省
  onConfirmProvince(e){
    this.setData({
        provinceId: e.detail.value.id,
        provinceName: e.detail.value.text,
        provinceObj:e.detail.value.obj,
  
        cityId:null,
        cityName:'',
        cityObj:null,
  
        districtId:null,
        districtName:'',
        districtObj:null,
  
        valueSearchProvince:'',
        disabled: false
    });

    this.onCloseProvince();
  },

  //显示城市
  onShowCity(){
    this.setData({
			showCity: true
    })
    //查询城市
    this.findCity();
  },

  //查询城市
  findCity(){
    let param = {
      isAuth: false,
      className: 'city',
      data: {
        searchAll: true,
        level:'2',
        fid:this.data.provinceId,	
        selectFields: ['id','name']
      }
    }
    
    //名称模糊查询
    if(this.data.valueSearchCity){
      param.data.name='%'+this.data.valueSearchCity+'%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          cityList: arr
        })
      }  
    }).catch((error) => {                
    })
  },

  //隐藏城市
  onCloseCity(){
    this.setData({
			showCity: false
    })
  },

  //确认城市
  onConfirmCity(e){
    this.setData({
        cityId: e.detail.value.id,
        cityName: e.detail.value.text,
        cityObj:e.detail.value.obj,
  
        districtId:null,
        districtName:'',
        districtObj:null,
  
        valueSearchCity:'',
        disabled: false
    });

    this.onCloseCity();
  },

  //显示区
  onShowDistrict(){
    this.setData({
			showDistrict: true
    })
    //查询区
    this.findDistrict();
  },

  //查询区
  findDistrict(){
    let param = {
      isAuth: false,
      className: 'city',
      data: {
        searchAll: true,
        level:'3',
        fid:this.data.cityId,	
        selectFields: ['id','name']
      }
    }
    
    //名称模糊查询
    if(this.data.valueSearchDistrict){
      param.data.name='%'+this.data.valueSearchDistrict+'%';
    }  

    CommonService.goFindList(param).then(res=>{ 
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          districtList: arr
        })
      }  
    }).catch((error) => {                
    })
  },

  //隐藏区
  onCloseDistrict(){
    this.setData({
			showDistrict: false
    })
  },

  //确认区
  onConfirmDistrict(e){
    this.setData({
        districtId: e.detail.value.id,
        districtName: e.detail.value.text,
        districtObj:e.detail.value.obj,
        valueSearchDistrict:'',
        disabled: false
    });

    this.onCloseDistrict();
  },

  //更新上级部门
  updateFather(id){
    let param = {
      className: 'depart',
      data: {
        filter: {
          id:id
        },
        update: {
          set: {
            hasChildren:true
          }
        }
      }
    }
    
    CommonService.goUpdate(param).then(res => {
    }).catch((error) => {
    })
  },

  //选择省-搜索
  onChangeProvince(e){
    this.setData({
      valueSearchProvince: e.detail
    })
    //查询
    this.findProvince();
  },

  //选择市-搜索
  onChangeCity(e){
    this.setData({
      valueSearchCity: e.detail
    })
    //查询
    this.findCity();
  },

  //选择区-搜索
  onChangeDistrict(e){
    this.setData({
      valueSearchDistrict: e.detail
    })
    //查询
    this.findDistrict();
  },

  //关联查询字段更新到设备表
  updateEquipment(obj){
    let param={
      departId:obj.id
    }
    CommonService.updateEquipmentAll(param).then(res=>{
    }).catch((error) => {
    })
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //显示父级
  onShowFather(){
    this.setData({
		showFather: true
    })
    this.getFatherList();
  },

  //查询父级
  getFatherList(){
    this.setData({
      fatherList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        complex:[{
            or:{
                "companyId":this.data.editInfo.companyId,
                "fid":this.data.editInfo.companyId
            }
        }],
        searchAll: true,
        selectFields: ['id','name','companyId','partnerId','fid','level']
      }
    }

    //模糊查询
    if(this.data.valueSearchFather){
      param.data.name='%' + this.data.valueSearchFather + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          fatherList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏父级
  onCloseFather(){
    this.setData({
      showFather: false,
      valueSearchFather:''
    })
  },

  //确认父级
  onConfirmFather(e){
    let companyId='editInfo.companyId';
    let partnerId='editInfo.partnerId';
    let fid='editInfo.fid';
    let fatherName='editInfo.fatherName';
    let level='editInfo.level'; 

    let obj=e.detail.value.obj;

    this.setData({
      [companyId]: obj.companyId,
      [partnerId]: obj.partnerId,
      [fid]: obj.id,
      [fatherName]: obj.name,
      [level]: obj.level+1,
      disabled: false
    })
    this.onCloseFather();
  },

  //搜索父级
  onChangeFatherVal(e){
    this.setData({
      valueSearchFather: e.detail
    })
    this.getFatherList();
  },

  //根据id查询名称
  getDepartName(id){
    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        id: id, 
        selectFields: ['name']
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(res.data.data.result[0].name);
        } else {
          resolve(null);
        }
      }).catch((error) => {
        resolve(null);
      })
    });  
  },

  //显示大区
  onShowRegion(){
    this.setData({
			showRegion: true
    })
    this.getRegionList();
  },

  //查询大区
  getRegionList(){
    this.setData({
      regionList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        companyId:this.data.editInfo.companyId,
        searchAll: true,
        isRegion: true,
        selectFields: ['id','name']
      }
    }
   
    if(this.data.valueSearchRegion){
      param.data.name='%' + this.data.valueSearchRegion + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          regionList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏大区
  onCloseRegion(){
    this.setData({
      showRegion: false,
      valueSearchRegion:''
    })
  },

  //确认大区
  onConfirmRegion(e){
    let rid='editInfo.rid';
    let regionId='editInfo.regionId';
    let regionName='editInfo.regionName';

    this.setData({
      [rid]: e.detail.value.id,
      [regionId]: e.detail.value.id,
      [regionName]: e.detail.value.text,
      disabled: false
    })

    this.onCloseRegion();
  },

  //搜索大区
  onChangeRegionVal(e){
    this.setData({
      valueSearchRegion: e.detail
    })
    this.getRegionList();
  },

  //清除大区选择
  onCancelRegion(){
    let rid='editInfo.rid';
    let regionName='editInfo.regionName';

    this.setData({
      [rid]:null,
      [regionName]:''
    })

    this.onCloseRegion();
  },

  //是否物业项目
  onChangeIsProject(event) {
    let isProject='editInfo.isProject';
    this.setData({
      [isProject]: event.detail
    })
  },

  //是否大区
  onChangeIsRegion(event) {
    let isRegion='editInfo.isRegion';
    this.setData({
      [isRegion]: event.detail,
    })
  },

  //是否保洁供应方
  onChangeCleaning(event) {
    let isCleaningSupplier='editInfo.isCleaningSupplier';
    this.setData({
      [isCleaningSupplier]: event.detail,
    })
  },

  //显示保洁供应方
  onShowClean(){
    this.setData({
			showClean: true
    })
    this.getCleanList();
  },

  //查询保洁供应方
  getCleanList(){
    this.setData({
      cleanList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        searchAll:true,
        type:4,
        level:1,
        selectFields:["id","name"]
      }
    }
   
    if(this.data.valueSearchClean){
      param.data.name='%' + this.data.valueSearchClean + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          cleanList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏保洁供应方
  onCloseClean(){
    this.setData({
      showClean: false,
      valueSearchClean:''
    })
  },

  //确认保洁供应方
  onConfirmClean(e){
    let cleaningSupplier='editInfo.cleaningSupplier';
    let cleanName='editInfo.cleanName';  

    this.setData({
      [cleaningSupplier]: [e.detail.value.id],
      [cleanName]: e.detail.value.text,
      disabled: false
    })
    this.onCloseClean();
  },

  //搜索保洁供应方
  onChangeCleanVal(e){
    this.setData({
      valueSearchClean: e.detail
    })
    this.getCleanList();
  },

  //清除保洁供应方选择
  onCancelClean(){
    let cleaningSupplier='editInfo.cleaningSupplier';
    let cleanName='editInfo.cleanName';

    this.setData({
      [cleaningSupplier]:null,
      [cleanName]:''
    })

    this.onCloseClean();
  },

  //项目名是否重复
  isExist(name){
    let param={
      isAuth:false,
      className:'depart',
      data:{
        name:name,
        companyId: this.data.editInfo.companyId,
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        selectFields:["id"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //同步pcsql数据库
  syncPcsql(id){
    let param={
      id: id
    }
    CommonService.syncDepart(param).then(res=>{
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})